package cn.com.wdjedu.androidapp.wjeduandroid.ui.userfragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.wdjedu.androidapp.wjeduandroid.Login;
import cn.com.wdjedu.androidapp.wjeduandroid.R;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.MvpFragment;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.user.UserPresenter;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.user.Userview;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.Constanct;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by samson on 26/11/2016.
 */

public class UserFragment extends MvpFragment<UserPresenter> implements Userview {

    @BindView(R.id.textViewUser)
    TextView textViewUser;
    @BindView(R.id.meLinearLayoutLogout)
    LinearLayout meLinearLayoutLogout;
    @BindView(R.id.progressBar3)
    ProgressBar progressBar3;
//    @BindView(R.id.user_form)
//    ScrollView userForm;
    @BindView(R.id.textViewLogout)
    TextView textViewLogout;
    private View view;
    private static final String FRAGMENT_USER = "fragment_user";

    /**
     * 点击半透明化设置
     */
    private ImageView ViewCourse;
    private View.OnTouchListener clickCourse;
    private ImageView ViewCollect;
    private View.OnTouchListener clickCollect;
    private ImageView ViewCache;
    private View.OnTouchListener clickCache;
    private TextView txtCourse;
    private TextView txtCollect;
    private TextView txtCache;

    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;

    //退出登录
    private UserLogoutTask mAuthTask = null;
    //请求超时更新线程
    private Runnable updateThread_Overtime;

    //计时器
    private CountDownTimer timer;
    /**
     * 创建新实例
     *
     * @param index
     * @return
     */
    public static UserFragment newInstance(int index) {
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_USER, index);
        UserFragment fragment = new UserFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_user, null);
            ButterKnife.bind(this, view);
            //获得索引值
            Bundle bundle = getArguments();
            if (bundle != null) {
                int mCurIndex = bundle.getInt(FRAGMENT_USER);
            }
            isPrepared = true;
            lazyLoad();
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        initFunc();
        initView(view);

        ButterKnife.bind(this, view);
        return view;
    }

    private void initView(View v) {
        //控件点击后改变透明度
        ViewCourse = (ImageView) v.findViewById(R.id.imageView6);
        ViewCourse.setOnTouchListener(clickCourse);
        ViewCollect = (ImageView) v.findViewById(R.id.mystore);
        ViewCollect.setOnTouchListener(clickCollect);
        ViewCache = (ImageView) v.findViewById(R.id.myhuancun);
        ViewCache.setOnTouchListener(clickCache);
        txtCourse = (TextView) v.findViewById(R.id.textViewMyCourse);
        txtCollect = (TextView) v.findViewById(R.id.textViewCollect);
        txtCache = (TextView) v.findViewById(R.id.textViewHuanCun);

        if (Constanct.USER_PHONE != "") {
            textViewUser.setText(Constanct.USER_PHONE);
            textViewLogout.setText("注销");
        }
        else{
            textViewUser.setText("东方标准X");
            textViewLogout.setText("登录");
        }

        //请求超时时更新线程
         updateThread_Overtime = new Runnable() {
            @Override
            public void run() {
                try {
                    //更新UI
                    Toast.makeText(getActivity().getApplicationContext(), "请求超时,请检查网络", Toast.LENGTH_SHORT).show();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        };

    }


    //初始化点击事件
    private void initFunc() {
        clickCourse = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.d("Test", "onTouchDown: 66666666666666666666666666666666" + v.getId());
                    Drawable image;
                    image = ViewCourse.getDrawable();
                    image.mutate().setAlpha(100);
                    ViewCourse.setImageDrawable(image);

                    txtCourse.setTextColor(Color.argb(100, 100, 100, 0));
                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    Log.d("Test", "onTouchUp: 777777777777777777777");
                    Drawable image;
                    image = ViewCourse.getDrawable();
                    image.mutate().setAlpha(255);
                    ViewCourse.setImageDrawable(image);

                    txtCourse.setTextColor(Color.argb(255, 6, 6, 6));
                    return true;
                }
                return false;
            }
        };

        clickCollect = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.d("Test", "onTouchDown: 66666666666666666666666666666666");
                    Drawable image;
                    image = ViewCollect.getDrawable();
                    image.mutate().setAlpha(100);
                    ViewCollect.setImageDrawable(image);

                    txtCollect.setTextColor(Color.argb(100, 100, 100, 0));
                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    Log.d("Test", "onTouchUp: 777777777777777777777");
                    Drawable image;
                    image = ViewCollect.getDrawable();
                    image.mutate().setAlpha(255);
                    ViewCollect.setImageDrawable(image);

                    txtCollect.setTextColor(Color.argb(255, 6, 6, 6));
                    return true;
                }
                return false;
            }
        };

        clickCache = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.d("Test", "onTouchDown: 66666666666666666666666666666666");
                    Drawable image;
                    image = ViewCache.getDrawable();
                    image.mutate().setAlpha(100);
                    ViewCache.setImageDrawable(image);

                    txtCache.setTextColor(Color.argb(100, 100, 100, 0));
                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    Log.d("Test", "onTouchUp: 777777777777777777777");
                    Drawable image;
                    image = ViewCache.getDrawable();
                    image.mutate().setAlpha(255);
                    ViewCache.setImageDrawable(image);
                    txtCache.setTextColor(Color.argb(255, 6, 6, 6));
                    return true;
                }
                return false;
            }
        };

//        userForm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
//                    showProgress(false);
//                    mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
//                    mAuthTask = null;
//                    timer.cancel();
//                }
//            }
//        });

        meLinearLayoutLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constanct.USER_TOKEN != "") {
                    mAuthTask = new UserLogoutTask(Constanct.USER_TOKEN);
                    mAuthTask.execute((Void) null);
                    showProgress(true);
                    //请求超时时
                  timer = new CountDownTimer(10000, 1000) {
                        public void onTick(long millisUntilFinished) {
                        }
                        public void onFinish() {
                            getActivity().runOnUiThread(updateThread_Overtime);
                            if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                                showProgress(false);
                                mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                                mAuthTask = null;
                                timer.cancel();
                            }
                        }
                    };
                    timer.start();
                } else {
                    startActivity(new Intent(getActivity().getApplication(), Login.class));
                    getActivity().finish();
                }
            }
        });
    }

    /**
     * Shows the progress UI and hides the regist form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

//            userForm.setVisibility(show ? View.GONE : View.VISIBLE);
//            userForm.animate().setDuration(shortAnimTime).alpha(
//                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    userForm.setVisibility(show ? View.GONE : View.VISIBLE);
//                }
//            });

            progressBar3.setVisibility(show ? View.VISIBLE : View.GONE);
            progressBar3.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    progressBar3.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            progressBar3.setVisibility(show ? View.VISIBLE : View.GONE);
          //  userForm.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    protected void onInvisible() {
        //初始化界面
        if (view != null) {


        }
        super.onInvisible();
    }


    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }

    }

    @Override
    public void onResume() {
        super.onResume();

    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String error) {

    }

    @Override
    protected UserPresenter createPresenter() {
        return null;
    }

    //检查网络
    private boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLogoutTask extends AsyncTask<Void, Void, String> {

        private final String mToken;

        UserLogoutTask(String token) {
            mToken = token;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (!isNetWorkConnected(getActivity().getApplicationContext()))
            {
//              RegistActivity.this.runOnUiThread(updateThread_failed);
                Toast.makeText(getActivity().getApplicationContext(), "请求失败,请检查网络", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            String result = null;
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("token", mToken);

            RequestBody body = builder.build();
            Request request = new Request.Builder()
                    .url(Constanct.DOMAIN+"common/logout")
                    .post(body)
                    .build();
            Response response = null;
            try {

                response = client.newCall(request).execute();
                result = response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                showProgress(false);
                mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                mAuthTask = null;
                timer.cancel();
            }
            // Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_LONG).show();
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONObject jsonObject2 = new JSONObject(jsonObject.get("resultData").toString());

                switch (Integer.parseInt(jsonObject2.get("code").toString())) {
                    case 200:
                        //Toast.makeText(getApplicationContext(), "" + jsonObject2.get("message"), Toast.LENGTH_SHORT).show();
                        Toast.makeText(getActivity().getApplicationContext(), "注销成功", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getActivity().getApplication(), Login.class));
                        getActivity().finish();
                        break;
                    case 201:
//                        mAuthTask = null;
//                        showProgress(false);
                        Toast.makeText(getActivity().getApplicationContext(), "注销失败，请检查网络", Toast.LENGTH_SHORT).show();
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onPostExecute(s);
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
